package com.zhugang.week14.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @program algorithms
 * @description: CyclicBarrierTest
 * @author: chanzhugang
 * @create: 2022/09/16 10:40
 */
public class CyclicBarrierTest {

    CyclicBarrier barrier;
    int page = 0;

    public CyclicBarrierTest() {
        // 回调执行
        barrier = new CyclicBarrier(2, () -> {

            System.out.println("sync...:" + page);
            page++;
        });
    }

    /**
     * 准备商品
     */
    void prepareProducts() {
        while (page < 1000) {

            try {
                System.out.println("fetch product...");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 准备发货单
     */
    void prepareDeliveryOrders() {
        while (page < 1000) {
            try {
                System.out.println("fetch delivery order...");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 启动两个线程
     */
    void run() {
        // lambda ==> method reference

        new Thread(this::prepareProducts).start();
        new Thread(this::prepareDeliveryOrders).start();
    }

    public static void main(String[] argv) {
        CyclicBarrierTest test = new CyclicBarrierTest();
        test.run();
    }
}